#include<iostream>
#include<cstring>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>


int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        std::cout<<"Usager: ./client ip port"<<std::endl;
        exit(1);
    }
    int sockfd=socket(AF_INET,NULL,SOCK_DGRAM);
    if(sockfd<0)
    {
        std::cout<<"socket fail!"<<std::endl;
        exit(2);
    }
    //客户端不需要显式绑定ip与端口

    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    struct in_addr addr;
    inet_pton(AF_INET, argv[1], &addr);
    server.sin_family=AF_INET;
    server.sin_port=htons(std::stoi(argv[2]));
    server.sin_addr=addr;
    socklen_t len=sizeof(server);
    while(1)
    {
        struct sockaddr_in peer;
        socklen_t n=sizeof(peer);
        std::string line;
        std::cout<<"Please Enter:"<<std::endl;
        getline(std::cin,line);
        sendto(sockfd,line.c_str(),line.size(),0,(const struct sockaddr*)&server,len);

        //接受来自服务端的echo信息：
        char buffer[1024];
        int s=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&n);
        if(s<0)
        {
            std::cout<<"recvfrom fail!"<<std::endl;
            return;
        }
        buffer[s]='0';
        std::cout<<buffer<<std::endl;
    }
    return 0;
}